package com.mssh.login.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2022/08/27/9:15
 * @Description:
 */
public class SecurityUtil {

    /**
     * @Description sha1方法
     * @param plainPassword 需要散列字符串
     * @param salt 盐字符串
     * @return
     */
    public static String hashPassword(String plainPassword, String salt) {
        String algorithmName = "SHA-256";
        int iterations = 2048;

        SimpleHash hash = new SimpleHash(
                algorithmName,
                plainPassword,
                salt != null ? ByteSource.Util.bytes(salt) : null,
                iterations
        );
        // 转换为十六进制（因 storedCredentialsHexEncoded=true）
        return hash.toHex();
    }

    /**
     * @Description 随机获得salt字符串
     * @return
     */
    public static String generateSalt(){
        return new SecureRandomNumberGenerator().nextBytes(16).toHex();
    }

    /**
     * @Description 生成密码字符密文和salt密文
     * @param
     * @return
     */
    public static Map<String,String> entryptPassword(String passwordPlain) {
        Map<String,String> map = new HashMap<>();
        String salt = generateSalt();
        String password = hashPassword(passwordPlain,salt);
        map.put("salt", salt);
        map.put("password", password);
        return map;
    }

    /**
     * @Description 生成密码字符密文和salt密文
     * @param
     * @return
     */
    public static String entryptPwdBySalt(String passwordPlain, String salt) throws Exception {
        if(StringUtils.isEmpty(passwordPlain) || StringUtils.isEmpty(salt)){
            throw new Exception("密码或盐不允许为空！");
        }
        Map<String,String> map = new HashMap<>();
        String password = hashPassword(passwordPlain, salt);
        return password;
    }

    /**
     * 生成账号
     * @return
     */
    public static String productAccount(){
        Random random = new Random();
        String account = "";
        for (int i = 0; i < 10; i++) {
            account += String.valueOf(random.nextInt(10));
        }
        return account;
    }
}
